﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using TjZheng.Mvc;
using TjZheng.Framework;
using TjZheng.SSO;

namespace TjZheng.SSO.Process
{
    public class BenzAuthFilter : TjZhengActionFilter
    {
        public SSOPowerType SSOPowerType { get; set; }
        public BenzAuthFilter(SSOPowerType ssoPowerType)
        {
            this.SSOPowerType = ssoPowerType;
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (this.SSOPowerType == SSOPowerType.None)
            {
                return;
            }
            InvokeResult objInvokeResult = new InvokeResult();
            string userId = CookieHelper.GetCookieValue("UserId");
            if (userId.IsNoNull())
            {
                objInvokeResult = ("http://tjzheng.sso.com/api/ssoapi/" + userId).CreateHttpGet<InvokeResult>();
            }
            var Request = filterContext.HttpContext.Request;
            if (userId.IsNull() || objInvokeResult.ResultCode != "Success")
            {
                CookieHelper.RemoveCookie("UserId");
                if (Request.IsAjaxRequest())
                {
                    objInvokeResult.ResultMessage = "对不起，请先登录";
                    filterContext.Result = new JsonResult
                    {
                        Data = objInvokeResult,
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    //todo：回调地址配置化，这边暂时写死
                    string callback = Request.GetDomain() + "/benz/target?targeturl=" + Request.Url.ToString().EncodeUrl();
                    string redirectUrl = "http://tjzheng.sso.com/benzuser/login?callback=" + callback.EncodeUrl();
                    filterContext.Result = new RedirectResult(redirectUrl);
                }
                return;
            }
            filterContext.HttpContext.SetItems("UserInfo", objInvokeResult.Data);
        }
    }
}
